// components/calendar/calendar.js
const util = require("../../pages/utils/util.js");

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    start: {
      type: String,
      value: '2020-03-27',
      // observer: function (e) {
      //   this.setData({ startDate: e });
      //   this._setViewMode(this.properties.viewMode)
      // }
    },
    end: {
      type: String,
      value: '2028-03-27',
      // observer: function (e) {
      //   this.setData({ endDate: e });
      //   this._setViewMode(this.properties.viewMode)
      // }
    },
    viewMode: {
      type: String,
      value: 'days' // weeks, months
    },
    /**
     * 当前时间
     */
    value: {
      type: String,
      value: util.formatTime(new Date(Date.now())).substr(0, 10)
    },

    itemColors: { // 单元格的指定时间
      type: Array,
      value: []
    }
  },

  // externalClasses: ['calendar-item-gary', 'calendar-item'],

  observers: {
    // "value": function(value){
    //   this._setViewMode(this.properties.viewMode);
    // },
    // "value, itemColors, viewMode, start, end": function () {
    "valu, itemColors": function () {
      //   this.setData({mode: viewMode});
      // },
      // "mode": function(mode){
      // 修改mode
      this._setItems();
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '2020年3月',
    mode: 'days',
    items: [],
    curYear: 2020,
    curMonth: 2
  },

  /**
   * 组件的方法列表
   */
  methods: {

    _setItems() {
      let value = this.properties.value;
      var viewMode = this.properties.viewMode;
      if (!value) {
        value = util.formatTime(new Date(Date.now())).substr(0, 10);
      }
      if (!['days', 'weeks', 'months'].indexOf(viewMode) < 0) {
        viewMode = 'days';
      }
      if (!this.properties.start || !this.properties.end) {
        return;
      }
      let today = util.formatTime(new Date(Date.now())).substr(0, 10);
      console.log('today:',today)
      let d = new Date(Date.parse(value));
     // console.log('today:',d)
      const curYear = d.getFullYear();
      const curMonth = d.getMonth() + 1;
      const firstDay = this.getFirstDayOfWeek(curYear, curMonth);
      const weeksCh = ['日', '一', '二', '三', '四', '五', '六'];
      // this.calculateEmptyGrids(curYear, curMonth);
      // this.calculateDays(curYear, curMonth);

      this.setData({
        today,
        curYear,
        curMonth,
        weeksCh
      });

      var items = [];
      switch (viewMode) {
        case 'days':
          let emptyGrids = this.calculateEmptyGrids(curYear, curMonth);
          //TODO 判断当前时间，取日期值
          items = emptyGrids.concat(this.calculateDays(curYear, curMonth)).concat(this.calculateLastEmptyGrids(curYear, curMonth));
          console.log(items)
          this.setData({
            title: `${curYear}年${curMonth}月`
          });
          break;
        case 'weeks':
          //TODO 判断当前时间，取周值
          this.setData({
            title: `${curYear}年${curMonth}月`
          });

          var dd = new Date(curYear, curMonth - 1, firstDay === 0 ? 2 : (2 - firstDay));
          while (dd.getMonth() <= curMonth - 1) {
            let d1 = new Date(dd);
            d1.setDate(d1.getDate() + 6);
            items.push({
              title: `第${weeksCh[items.length + 1]}周(${util.formatTime(dd).substr(5, 5)}~${util.formatTime(d1).substr(5, 5)})`,
              index: items.length,
              value: util.formatTime(dd).substr(0, 10),
              itemclass: (util.formatTime(d1).substr(0, 10) < this.data.startDate || util.formatTime(dd).substr(0, 10) > this.data.endDate) ? 'calendar-item-gary' : ''
            });
            // console.log(util.formatTime(dd).substr(10), this.data.startDate, util.formatTime(d1).substr(10), this.data.endDate);
            dd.setDate(dd.getDate() + 7);
          }
          break;
        case 'months':
          for (var i = 1; i <= 12; i++) {
            items.push({
              title: `${i}月`,
              index: i,
              value: `${curYear}-${i <= 9 ? '0' : ''}${i}`,
              itemclass: (`${curYear}-${i <= 9 ? '0' : ''}${i}-31` < this.data.startDate || `${curYear}-${i <= 9 ? '0' : ''}${i}-01` > this.data.endDate) ? 'calendar-item-gary' : ''
            });
          }
          this.setData({
            title: curYear + '年'
          });
          break;
          // default:
          // viewMode = "days";
          // for(var i=0;i<31;i++){
          //   items.push(i);
          // }
      }

      if (Array.isArray(this.properties.itemColors)) {
        this.properties.itemColors.map(item => {
          for (var i = 0; i < items.length; i++) {
            if (item.date === items[i].value) {
              items[i].style = item.style || '';
              items[i].itemclass = item.class;
              items[i].tip = item.tip;
              break;
            }
          }
        });
      }

      // console.log(items);
      this.setData({
        items
      });
    },

    getThisMonthDays(year, month) {
      return new Date(year, month, 0).getDate();
    },
    getFirstDayOfWeek(year, month) {
      return new Date(Date.UTC(year, month - 1, 1)).getDay();
    },
    getLastDayOfWeek(year, month) {
      return new Date(Date.UTC(year, month, 0)).getDay();
    },
    calculateEmptyGrids(year, month) {
      const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
      let emptyGrids = [];
      if (firstDayOfWeek > 0) {
        // let d = new Date(year, month, 0);
        var d;
        for (let i = 1 - firstDayOfWeek; i <= 0; i++) {
          d = new Date(year, month - 1, i);
          emptyGrids.push({
            title: d.getDate(),
            index: i,
            value: util.formatTime(d).substr(0, 10),
            itemclass: 'calendar-item-gary'
          });
        }
      }
      return emptyGrids;
    },
    calculateLastEmptyGrids(year, month) {
      const lastDayOfWeek = this.getLastDayOfWeek(year, month);
      let emptyGrids = [];
      if (lastDayOfWeek >= 0) {
        for (let i = 1; i <= 7 - lastDayOfWeek - 1; i++) {
          let d = new Date(year, month, i);
          d.setDate(i);
          emptyGrids.push({
            title: d.getDate(),
            index: i,
            value: util.formatTime(d).substr(0, 10),
            itemclass: 'calendar-item-gary'
          });
        }
      }
      return emptyGrids;
    },


    calculateDays(year, month) {
      let days = [];
      const thisMonthDays = this.getThisMonthDays(year, month);
      let d = new Date(year, month - 1, 1);
      for (var i = 1; i <= thisMonthDays; i++) {
        d.setDate(i);
        let item = {
          title: i,
          index: i,
          value: util.formatTime(d).substr(0, 10)
        };
        if (this.properties.end && item.value > this.properties.end || this.properties.start && item.value < this.properties.start) {
          item.itemclass = 'calendar-item-gary';
        } else {
          item.itemclass = '';
        }
        days.push(item);
      }

      return days;
    },


    handleCalendar(e) {
      const handle = e.currentTarget.dataset.handle;
      var value = this.properties.value;
      let d = new Date(Date.parse(value));
      const curYear = d.getFullYear();
      const curMonth = d.getMonth();
      if (handle === 'prev') {
        if (this.properties.start && this.properties.start.substr(0, 7) >= value.substr(0, 7)) {
          return;
        }
        if (this.data.viewMode === 'months') {
          value = util.formatTime(new Date(curYear - 1, curMonth, 1)).substr(0, 10);
        } else {
          value = util.formatTime(new Date(curYear, curMonth - 1, 1)).substr(0, 10);
        }
      } else {
        if (this.properties.end && this.properties.end.substr(0, 7) <= value.substr(0, 7)) {
          return;
        }
        if (this.data.viewMode === 'months') {
          value = util.formatTime(new Date(curYear + 1, curMonth, 1)).substr(0, 10);
        } else {
          value = util.formatTime(new Date(curYear, curMonth + 1, 1)).substr(0, 10);
        }
      }
      this.properties.value = value;
      this.triggerEvent('datechange', {
        value
      });
      this._setItems();
    },


    _itemClick(e) {
      var {
        index,
        value
      } = e.currentTarget.dataset;
      console.log('xxx', value);
      this.triggerEvent('itemclick', {
        index,
        value
      });
      this.setData({
        clickday: value
      })
    },

    /**
     * 日期下拉选择控件值变化事件
     * @param {} e 
     */
    _dateChange(e) {
      console.log(e.detail);
      this.properties.value = e.detail.value + "-01";
      this.triggerEvent('datechange', {
        value: this.properties.value
      });
      this._setItems();
    }


  }
})